﻿using System;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using Google.Protobuf.Examples.AddressBook;
using System.Collections.Generic;

namespace UdpPB_Demo
{
	public class UDPConnection
	{
		
	}

	public class TestUDPServer
	{
		public static Dictionary<System.Type, int> protoIds = new Dictionary<System.Type, int>()
		{
			{typeof(MovePosC2S), 1},
			{typeof(UseSkillC2S), 2},
			{typeof(Data), 3},
		};

		public UdpClient udpClient;
        Program.MessageProcess messageProcess = new Program.MessageProcess();

		public TestUDPServer()
		{
            udpClient = new UdpClient(5050);
		}
		public void Receive()
		{
			Console.WriteLine("BeforeReceive");

			IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 4040);

			var data = udpClient.Receive(ref endPoint);

			Console.WriteLine("ReceiveFrom:" + endPoint.ToString());
			messageProcess.Process(data, data.Length);


			var data1 = messageProcess.msgData;
			var str = data1.ToString();

			var dataSend = new Data()
			{
				Data_ = str,
			};

			var memStream = new MemoryStream();
			var co = new Google.Protobuf.CodedOutputStream(memStream);
			dataSend.WriteTo(co);
			co.Flush();

			var data2 = memStream.ToArray();
			var len = (UInt16)data2.Length;

            //  HEAD, TYPE, FRAME_ID,  BODY
			var byteArray = new byte[2 + 2 + 1 + len];
			var blen = BitConverter.GetBytes(len);
			var typeId = (UInt16)protoIds[dataSend.GetType()];
			var typeArr = BitConverter.GetBytes(typeId);

			byte fid = (byte)0;
			var frameArr = BitConverter.GetBytes(fid);
			Array.Copy(blen, byteArray, 2);
			Array.Copy(typeArr, 0, byteArray, 2, 2);
			Array.Copy(frameArr, 0, byteArray, 4, 1);
			Array.Copy(data2, 0, byteArray, 5, len);

			udpClient.Send(byteArray, byteArray.Length, endPoint);
		}

		public void Send()
		{
			
		}

	}
}

